﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PesticideManage.API.Data;
using PesticideManage.API.Extensions;
using PesticideManage.API.Services.Identity.RoleAggregate;
using PesticideManage.API.Services.Menus;

namespace PesticideManage.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MenusController : ControllerBase
    {
        private readonly PesticideContext _context;

        public MenusController(PesticideContext context)
        {
            _context = context;
        }

        // GET: api/Menus
        [HttpGet]
        public ActionResult<IEnumerable<Menu>> GetMenus()
        {
            int userId = User.GetId();
            var menus = _context.Users
                .AsNoTracking()
                .Include(u => u.Roles)
                .Where(u => u.Id == userId)
                .SelectMany(u => u.Roles)
                .SelectMany(r => r.Menus.Distinct())
                .Include(m => m.Children)
                .OrderBy(m => m.Order);
           
  
            if (menus is null)
            {
                return NotFound($"用户{User.Identity?.Name}不存在");
            }
            return Ok(menus);
        }

        // GET: api/Menus/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Menu>> GetMenu(string id)
        {
            if (_context.Menus == null)
            {
                return NotFound();
            }
            var menu = await _context.Menus.FindAsync(id);

            if (menu == null)
            {
                return NotFound();
            }

            return menu;
        }

        // PUT: api/Menus/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutMenu(string id, Menu menu)
        {
            if (id != menu.Name)
            {
                return BadRequest();
            }

            _context.Entry(menu).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MenuExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Menus
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<Menu>> PostMenu(Menu[] menus)
        {
            if (_context.Menus == null)
            {
                return Problem("Entity set 'PesticideContext.Menus'  is null.");
            }
            if (_context.Menus.Count() == 0)
            {
                Role admin = await _context.Roles.FirstAsync(r => r.Name == "admin");
                admin.Menus = menus;
            }
            else
            {
                _context.Menus.AddRange(menus);
            }

            await _context.SaveChangesAsync();


            return CreatedAtAction(nameof(GetMenus), null, menus);
        }

        // DELETE: api/Menus/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteMenu(string id)
        {
            if (_context.Menus == null)
            {
                return NotFound();
            }
            var menu = await _context.Menus.FindAsync(id);
            if (menu == null)
            {
                return NotFound();
            }

            _context.Menus.Remove(menu);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool MenuExists(string id)
        {
            return (_context.Menus?.Any(e => e.Name == id)).GetValueOrDefault();
        }
    }
}
